<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class WxCheckDramaTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

    public static $getDramaUrl = "https://api.weixin.qq.com/wxa/sec/vod/getdrama";

    public static $getMediaUrl = "https://api.weixin.qq.com/wxa/sec/vod/getmedia";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'getCheckDrama');
    }

    public function execute()
    {
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始定时获取剧目提审数据');
        $this->logger->info('获取短剧中提审的的数据');
        //获取需要获取任务的视频
        $playletData = Playlet::query()->where('drama_id','!=',0)->whereNotIn('drama_status',[0,3])->get();
        if($playletData->isNotEmpty()){

            $playletIds = [];

            foreach ($playletData as $playletDatum) {
                $playletIds[] = $playletDatum->id;
            }
            //查询关联表中的小程序ID
            $this->logger->info('查询关联表中的小程序ID,',$playletIds);
            $appletPlayletRelData = AppletPlayletRel::query()->whereIn('playlet_id',$playletIds)->where(['applet_id' => 10000])->select(['playlet_id','applet_id'])->orderBy('applet_id')->get();
            if($appletPlayletRelData->isNotEmpty()) {
                $appletIds = array();
                $appletPlayletKeyVal = array();
                //遍历获取对应关系和小程序ID
                foreach ($appletPlayletRelData as $appletPlayletRelDatum){

                    $appletPlayletKeyVal[$appletPlayletRelDatum->playlet_id][] = $appletPlayletRelDatum->applet_id;
                    $appletIds[] = $appletPlayletRelDatum->applet_id;

                }
                $appletIds = array_values(array_unique($appletIds));
                //查询小程序的ID 获取appID 和密钥
                $this->logger->info('查询小程序的ID 获取appID 和密钥');
                $appletData = Applet::query()->whereIn('id',$appletIds)->where(['type' => 1])->select(['id','name','app_id','app_secret'])->get();
                if($appletData->isNotEmpty()) {

                    $appletKeyVal = [];
                    foreach ($appletData as $appletDatum) {
                        $appletKeyVal[$appletDatum->id] = $appletDatum;
                    }
                    foreach ($playletData as $playletDatum) {
                        //短剧名称
                        $playlet_name = $playletDatum->name;
                        //获取对应的小程序accessToken,获取这个短剧绑定的小程序
                        $appletPlayletData = $appletPlayletKeyVal[$playletDatum->id];
                        $appletInfo = array();
                        foreach ($appletPlayletData as $appletPlayletDatum){
                            if(!empty($appletKeyVal[$appletPlayletDatum])){
                                $appletInfo = $appletKeyVal[$appletPlayletDatum];
                                break;
                            }
                        }

                        if(empty($appletInfo)){
                            $this->logger->error('获取绑定此短剧的小程序不存在:');
                            continue;
                        }

                        $applet_name = $appletInfo->name;
                        $this->logger->info('获取绑定此短剧的小程序token:'.$applet_name);
                        $accessToken = $this->getWxAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);
                        $this->logger->info('获取短剧审核数据:'.$playlet_name);

                        $dramaInfo = $this->getDramaInfo($playletDatum->drama_id,$accessToken);

                        if(!empty($dramaInfo) && !empty($dramaInfo['audit_detail'])){

                            $playletDatum->drama_status = $dramaInfo['audit_detail']['status'];
                            if(!empty($dramaInfo['audit_detail']['reason'])){
                                $playletDatum->drama_msg = $dramaInfo['audit_detail']['reason'];
                            }
                            $playletDatum->save();

                        }
                        $playletEpisodesData = PlayletEpisodes::query()->select(['id','old_media_id','media_id','media_status','is_upload','playlet_number_name'])
                            ->where('playlet_id',$playletDatum->id)
                            ->where('is_upload','!=',4)
                            ->where('media_status','!=',3)->where('media_id','!=',0)->get();

                        if($playletEpisodesData->isNotEmpty() && !empty($appletInfo)) {

                            $this->logger->info('开始遍历获取短剧剧集集数的审核数据');
                            foreach ($playletEpisodesData as $playletEpisodes){

                                $media_id = $playletEpisodes->media_id;

                                if(!empty($accessToken)){
                                    $this->logger->info('小程序：'.$applet_name.' 短剧：'.$playlet_name.' 获取短剧集数据进度 '.$playletEpisodes->playlet_number_name);
                                    $mediaInfo = $this->getMeDiaInfo($media_id,$accessToken);
                                    if(!empty($mediaInfo)){
                                        if(!empty($mediaInfo['audit_detail'])){

                                            if($playletEpisodes->is_upload == 3 && !empty($mediaInfo['audit_detail']['reason'])){
                                                $playletEpisodes->media_status_error = $mediaInfo['audit_detail']['reason'];
//                                                $playletEpisodes->is_upload = 1;
                                            }
                                            if($mediaInfo['audit_detail']['status'] == 2 && !empty($mediaInfo['audit_detail']['reason'])){
                                                if($playletEpisodes->is_upload == 3){
                                                    $playletEpisodes->media_status = 4;
                                                }

                                            }else{
                                                $playletEpisodes->media_status = $mediaInfo['audit_detail']['status'];
                                            }

                                            $playletEpisodes->save();
                                            $this->logger->info('小程序：'.$applet_name.' 短剧：'.$playlet_name.' 获取数据成功 '.$playletEpisodes->playlet_number_name);
                                        }else{

                                            if(!empty($media_id) && !empty($playletEpisodes->old_media_id)){
                                                $this->logger->info('短剧未通过：'.$applet_name.' 短剧：'.$playlet_name.' 替换集数');
                                                $playletEpisodes->media_status = 0;
                                                $playletEpisodes->save();
                                            }


                                            $this->logger->info('小程序：'.$applet_name.' 短剧：'.$playlet_name.' 获取审核数据失败');
                                        }
                                    }else{
                                        $this->logger->info('小程序：'.$applet_name.' 短剧：'.$playlet_name.' 获取数据失败');
                                    }
                                }else {
                                    $this->logger->error('小程序:' . $applet_name . ' 短剧:' . $playlet_name . ' 没有对应的token');
                                }
                            }
                        }else{
                            $this->logger->error('短剧没有绑定小程序或者短剧没有需要审核的集数');
                        }
                    }
                }else{
                    $this->logger->error('查询小程序ID：没有对应的小程序数据');
                }
            }else{
                $this->logger->error('查询关联表中的小程序ID：没有对应的短剧小程序数据');
            }
        }else{
            $this->logger->info('没有短剧审核数据');
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取剧目提审数据');
    }
    public function getWxAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');

        $key = 'wx_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'appid'    => $app_id,
                'secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'GET');

            if (!empty($accessTokenInfo['access_token'])){
                $accessToken = $accessTokenInfo['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        return $accessToken;
    }
    public function getMeDiaInfo($media_id,$accessToken){

        $params         = [
            "media_id"    => $media_id,
        ];
        $taskUrl = self::$getMediaUrl.'?access_token='.$accessToken;
        $this->logger->info('请求媒资数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求媒资Url：'.$taskUrl);
        //开始上传
        $postResult  = $this->request($params, $taskUrl,'POST');
        if($postResult['errcode'] == 0){
//            $this->logger->info('调用媒资接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
            return $postResult['media_info'];
        }else{
            $this->logger->error('调用媒资接口失败 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        }
        return false;
    }

    public function getDramaInfo($drama_id,$accessToken){

        $params         = [
            "drama_id"    => $drama_id,
        ];
        $taskUrl = self::$getDramaUrl.'?access_token='.$accessToken;
//        $this->logger->info('请求剧目信息数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求剧目信息Url：'.$taskUrl);
        //开始上传
        $postResult  = $this->request($params, $taskUrl,'POST');
        if($postResult['errcode'] == 0){
//            $this->logger->info('调用剧目信息接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
            return $postResult['drama_info'];
        }else{
            $this->logger->error('调用剧目信息接口失败 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        }
        return false;
    }




    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       =['Content-Type' => 'application/json;charset=utf-8', 'Accept' => 'application/json','Accept-Charset' => 'utf-8'];
        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;
        }
//        var_dump($requestParams);
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}